/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.jsf;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Utility class providing basic functionality to build URIs for calling the retabel rest interface
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 20:39 13.08.11
 *
 * @author Herbert
 * @version 1.0
 */
public class WebUriBuilder {

    // constants

    private static final String WEB_CONTEXT_ROOT = "/retabel";
    private static final String WEB_SERVLET_CONTEXT = "/services";

    protected static final String WEB_XMLSCHEMA_PATH = "/xsd/";

    private static final String WEB_SERVICE_RENDER = "/render";

    // private methods

    private static URI getServerURI() throws URISyntaxException {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

        String requestURL = request.getRequestURL().toString();
        requestURL = requestURL.substring(0, requestURL.indexOf(request.getContextPath()));

        URI uri = new URI(requestURL);
        uri = uri.resolve(WEB_CONTEXT_ROOT + WEB_SERVLET_CONTEXT + "/");

        return uri;
    }

    // public methods

    public static URI fromPath(String path) throws URISyntaxException {
        URI uri = getServerURI();

        if (path == null) {
            throw new IllegalArgumentException("path is null or empty");
        }

        while (path.startsWith("/")) {
            path = path.substring(1);
        }

        return uri.resolve(path);
    }

    public static URI getRenderServiceURI(String data, String config) throws URISyntaxException {
        return fromPath(WEB_SERVICE_RENDER);
    }
}
